The standard C library provides several functions to create temporary files and directories. These functions include mktemp
,
mkstemp
, mkstemps
and mkdtemp
, and they accept as a parameter a template
that defines the path
where the file (or directory) should be created. The filename part of the template
must contain at least six trailing "X"s to ensure the
uniqueness of the filename, since these "X"'s are replaced with a string that makes the filename unique.
Note that the template
parameter will be modified and therefore, it may not be a string constant, but should be declared as a
character array, instead.
#include <stdio.h>
#include <stdlib.h>
int create_tmp_file() {
char tmp_name[] = "example_XXXXX"; // `template` parameter only contains five "X"s
printf("raw template: %s\n", tmp_name);
int fd = mkstemp(tmp_name); // Noncompliant: `mkstemp` will fail due to an invalid template parameter.
if (fd == -1) {
perror("mkstemp failed");
return 1;
}
printf("unique name: %s\n", tmp_name);
return 0;
}